package ru.bytedog.artifact.cache.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ru.bytedog.artifact.cache.dto.CacheInfo;
import ru.bytedog.artifact.cache.service.CacheService;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Optional;

@Slf4j
@RestController
public class ArtifactCacheController {

    private final CacheService service;

    public ArtifactCacheController(CacheService service) {
        this.service = service;
    }

    @PostMapping("/{id}")
    public ResponseEntity<Void> handleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable String id) throws IOException {
        service.add(file, id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping
    public ResponseEntity<CacheInfo> info() {
        return ResponseEntity.ok()
                .body(service.getCacheInfo());
    }

    @GetMapping("/{id}")
    public ResponseEntity<Resource> download(@PathVariable String id) {
        Optional<byte[]> file = service.get(id);
        if (file.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(file.get()));
        return ResponseEntity.ok()
                .contentLength(file.get().length)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    @DeleteMapping
    public ResponseEntity<Void> clear() {
        service.clear();
        return ResponseEntity.noContent().build();
    }

}
